/**
 * Created by stouduo on 2016/4/12.
 */
'use strict';
$.ajaxSetup({
  async: false
});
var app = angular.module('cmsysApp', ['ui.router', 'ngAnimate']);
(function () {
  var userPrivileges, allPrivileges = {}, allPrivilegeUrls = {};
  allPrivilegeUrls.urls = [];
  $.get(baseUrl + '/user/getPrivileges').done(function (data) {
    userPrivileges = data.privileges;
  });
  $.get(baseUrl + '/privilege/privileges').done(function (data) {
    var privileges = data.privileges;
    for (var i = 0; i < privileges.length; i++) {
      if (userPrivileges.length > 0)
        for (var j = 0; j < userPrivileges.length; j++) {
          if (userPrivileges[j].name == privileges[i].name) {
            allPrivileges[privileges[i].name] = true;
            allPrivilegeUrls.urls.push(privileges[i].url);
            break;
          } else allPrivileges[privileges[i].name] = false;
        }
      else
        allPrivileges[privileges[i].name] = false;
    }
    app.constant('userPrivilegeUrls', allPrivilegeUrls)
      .constant('userPrivileges', allPrivileges)
      .directive('privilege', ['userPrivileges', function (userPrivileges) {
        return {
          restrict: 'A',
          link: function (scope, element, attrs) {
            var options = attrs.privilege.split(":");
            if (options.length == 1) {
              !userPrivileges[attrs.privilege] && element.hide();
            } else {
              if (!userPrivileges[options[0]]) {
                element.removeAttr('style');
                delete scope.$parent[options[1]];
              }
            }
          }
        }
      }])
      .run(
      ['$rootScope', '$state', '$stateParams', '$location', 'userPrivilegeUrls',
        function ($rootScope, $state, $stateParams, $location, userPrivilegeUrls) {
          $rootScope.$state = $state;
          $rootScope.$stateParams = $stateParams;
          $rootScope.$on('$locationChangeStart', function (event) {
            // console.log($location.path());
            var path = $location.path();
            if (path !== "/index"
              && path !== '/noPrivilege'
              && path !== '/activity'
              && path !== '/settings') {
              var flag = false;
              for (var i = 0; i < userPrivilegeUrls.urls.length; i++) {
                if ($location.path() == userPrivilegeUrls.urls[i]) {
                  flag = true;
                  break;
                }
              }
              if (!flag) {
                event.preventDefault();
                $location.path('/noPrivilege');
              }
            }
          })
        }]);
  });
})();
app.config(
  [
    '$stateProvider',
    '$urlRouterProvider',
    '$httpProvider',
    function ($stateProvider, $urlRouterProvider,
              $httpProvider) {
      $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
      $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
      $httpProvider.defaults.transformRequest = function (data) {
        if (data === undefined || data === '') {
          return data;
        }
        return $.param(data);
      };
      // $urlRouterProvider
      //   .otherwise('/index');
      $stateProvider
        .state(
          'index',
          {
            url: "/index",
            views: {
              "right": {
                templateUrl: "cmsys/app/views/home/right.html"
              }
            }
          })
        .state(
          'privilege',
          {
            url: "/privilege",
            views: {
              "right": {
                templateUrl: "cmsys/app/views/privilege/privilege.html",
                controller: 'privilegeCtrl'
              },
              "pagebar@privilege": {
                templateUrl: "cmsys/app/views/pagebar.html"
              }
            }
          })
        .state(
          'contractList',
          {
            url: "/contract/contractList",
            views: {
              "right": {
                templateUrl: "cmsys/app/views/contract/contractList.html",
                controller: 'contractCtrl'
              },
              "pagebar@contractList": {
                templateUrl: "cmsys/app/views/pagebar.html"
              }
            }
          })
        .state(
          'userList',
          {
            url: '/user/userList',
            views: {
              "right": {
                templateUrl: "cmsys/app/views/user/userList.html",
                controller: 'userCtrl'
              },
              "pagebar@userList": {
                templateUrl: "cmsys/app/views/pagebar.html"
              }
            }
          })
        .state(
          'projectList',
          {
            url: '/project/projectList',
            views: {
              "right": {
                templateUrl: "cmsys/app/views/project/projectList.html",
                controller: 'projectCtrl'
              },
              "pagebar@projectList": {
                templateUrl: "cmsys/app/views/pagebar.html"
              }
            }
          })
        .state('userInfo', {
          url: '/user/userInfo',
          views: {
            right: {
              templateUrl: "cmsys/app/views/user/userInfo.html",
              controller: 'userInfoCtrl'
            }
          }
        })
        .state('analysis', {
          url: '/analysis',
          views: {
            right: {
              templateUrl: "cmsys/app/views/analysis/analysis.html",
              controller: 'analysisCtrl'
            }
          }
        })
        .state('noPrivilege', {
          url: '/noPrivilege',
          views: {
            right: {
              templateUrl: "cmsys/app/views/noPrivilege.html",
            }
          }
        });
    }])
  .service('pageService', ['$http', '$q', function ($http, $q) {
    this.query = function (params) {
      var deferred = $q.defer();
      $http.get(params.url, {
        'params': params.conditions
      }).success(function (data) {
        deferred.resolve(data.page);
      }).error(function () {
        alert('网络堵车了。。。');
      });
      return deferred.promise;
    };
    this.loadData = function ($scope, page) {
      page.pageSize = page.pageSize + "";
      if (page.pageCount == 0)
        page.currentPage = 0;
      $scope.page = page;
      $scope.hidePre = $scope.page.currentPage <= 1;
      $scope.hideNext = $scope.page.currentPage >= $scope.page.pageCount;
    };
    this.changePS = function ($scope) {
      $scope.params.conditions.pageSize = $scope.page.pageSize;
    };
    this.changeCD = function ($scope) {
      $scope.params.conditions.condition = $scope.condition;
    };
  }])
  .service('baseService', ['$http', '$q', function ($http, $q) {
    this.query = function (query) {
      var deferred = $q.defer();
      $http.get(query.url, {'params': query.params}).success(function (data) {
        deferred.resolve(data);
      }).error(function () {
        alert("网络堵车了。。。");
      });
      return deferred.promise;
    };
    this.del = function (del) {
      $http.get(del.url, {'params': del.params}).success(function (data) {
        data && alert(data.message);
      }).error(function () {
        alert("网络堵车了。。。");
      });
    };

    this.edit = function (edit) {
      $http.post(edit.url, edit.params).success(function (data) {
        data && alert(data.message);
      }).error(function () {
        alert("网络堵车了。。。");
      })
    };
  }])
  .filter('highlightText', ['$sce', function ($sce) {
    return function (input, searchText) {
      input && (input = input + "");
      if (searchText && input) {
        input = input.replace(new RegExp('(' + searchText + ')', 'i'),
          '<span class="bg-orange disabled" style="color:red">$1</span>')
      }
      return $sce.trustAsHtml(input);
    };
  }]);
